The Dictionary Data Type

Dictionaries contain key-value pairs. Keys are like a list's indexes. Dictionaries are mutable. Variables hold references to dictionary values, not the dictionary value itself.

In [1]:
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
myCat['size']
Out[1]:
'fat'
In [2]:
'My cat has ' + myCat['color'] + ' fur.'
Out[2]:
'My cat has gray fur.'

Unlike list, Dictionaries are unordered. There is no "first" key-value pair in a dictionary.

In [3]:
spam = {12345: 'Luggage combination', 42: 'The Answer'}
[1, 2, 3] == [3, 2, 1]
Out[3]:
False
In [4]:
eggs = {'name': 'Zophie', 'species': 'cat'}
ham = {'species': 'cat', 'name': 'Zophie'}
eggs == ham
Out[4]:
True

KeyError

In [5]:
eggs = {'name': 'Zophie', 'species': 'cat'}
# eggs('color') # KeyError

In & not in

In [6]:
'name' in eggs
Out[6]:
True
In [7]:
'name' not in eggs
Out[7]:
False

Dictionary Methods

The keys(), values(), items() Methods

The keys() method will return list-like values of a dicitonary's keys

In [8]:
eggs = {'name': 'Zophie', 'species': 'cat'}
eggs.keys()
Out[8]:
dict_keys(['name', 'species'])
In [9]:
list(eggs.keys())
Out[9]:
['name', 'species']

The values() method will return list-like values of a dicitonary's values

In [10]:
eggs = {'name': 'Zophie', 'species': 'cat'}
list(eggs.values())
Out[10]:
['Zophie', 'cat']

The items() method will return list-like values of a dicitonary's keys and values

In [11]:
eggs = {'name': 'Zophie', 'species': 'cat'}
list(eggs.items())
Out[11]:
[('name', 'Zophie'), ('species', 'cat')]

Using Dictionary with For loops

In [12]:
for k in eggs.keys():
  print(k)
name
species
In [13]:
for v in eggs.values():
  print(v)
Zophie
cat
In [14]:
for k, v in eggs.items():
  print(k, v)
name Zophie
species cat

The below expression returns a tuple. Tuple: similar to list but immutable and use ()

In [15]:
for i in eggs.items():
  print(i)
('name', 'Zophie')
('species', 'cat')
In [16]:
'cat' in eggs.values()
Out[16]:
True

The get() Dictionary Method

The get() method can return a default value if a key doesn't exist. It can be used to prevent KeyError

In [17]:
eggs.get('name', 0)
Out[17]:
'Zophie'

No key named "age" in object "eggs", return 0

In [18]:
eggs.get('age', 0)
Out[18]:
0

The setdefault() Dictionary Method

The setdefault() dictionary method can set a value if a key doesn't exist.

In [19]:
eggs.setdefault('color', 'black')
eggs
Out[19]:
{'color': 'black', 'name': 'Zophie', 'species': 'cat'}
In [20]:
eggs.setdefault('color', 'orange')
eggs
Out[20]:
{'color': 'black', 'name': 'Zophie', 'species': 'cat'}

Example: Character Counting Program

In [21]:
message = "It was a bright cold day in April, and the clocks were striking thirteen"
count = {}

for character in message.upper():
  count.setdefault(character, 0)
  count[character] = count[character] + 1

print(count)
{'I': 7, 'T': 6, ' ': 13, 'W': 2, 'A': 5, 'S': 3, 'B': 1, 'R': 5, 'G': 2, 'H': 3, 'C': 3, 'O': 2, 'L': 3, 'D': 3, 'Y': 1, 'N': 4, 'P': 1, ',': 1, 'E': 5, 'K': 2}

Using Triple quotes

Use triple ticks to enclose a large block of text and to paste multi-line text (more on chapter 19) e.g. copy and paste the entire text of Shakespeare's 'Romeo & Juliet' in the program by adding ''' after "message = " and at the end of copied text in the program

The pprint Module

The pprint module's pprint() "pretty print" function can display a dictionary value cleanly and orderly.

In [22]:
import pprint

''' Same program here
Replace print(count) with '''

pprint.pprint(count)
{' ': 13,
 ',': 1,
 'A': 5,
 'B': 1,
 'C': 3,
 'D': 3,
 'E': 5,
 'G': 2,
 'H': 3,
 'I': 7,
 'K': 2,
 'L': 3,
 'N': 4,
 'O': 2,
 'P': 1,
 'R': 5,
 'S': 3,
 'T': 6,
 'W': 2,
 'Y': 1}

The pformat() function returns a string value of this output.

In [23]:
import pprint

''' Same program here
Replace print(count) with '''

rjtext = pprint.pformat(count)
print(rjtext)
{' ': 13,
 ',': 1,
 'A': 5,
 'B': 1,
 'C': 3,
 'D': 3,
 'E': 5,
 'G': 2,
 'H': 3,
 'I': 7,
 'K': 2,
 'L': 3,
 'N': 4,
 'O': 2,
 'P': 1,
 'R': 5,
 'S': 3,
 'T': 6,
 'W': 2,
 'Y': 1}

Data Structures

The .append() Method

In [24]:
cat = {'name': 'Zophie', 'age': 7, 'color': 'gray'}
allCats = [] # Blank list
allCats.append({'name': 'Zophie', 'age': 7, 'color': 'gray'})
allCats.append({'name': 'Pooka', 'age': 5, 'color': 'black'})
allCats.append({'name': 'Fat-tail', 'age': 5, 'color': 'gray'})

Example: Tic Tac Toe

img The slots of a tic-tac-toe board with their corresponding keys

In [25]:
theBoard = {
  'top-L':' ', 'top-M':' ', 'top-R':' ',
  'mid-L':' ', 'mid-M':' ', 'mid-R':' ',
  'low-L':' ', 'low-M':' ', 'low-R':' '
  }

import pprint
pprint.pprint(theBoard)
{'low-L': ' ',
 'low-M': ' ',
 'low-R': ' ',
 'mid-L': ' ',
 'mid-M': ' ',
 'mid-R': ' ',
 'top-L': ' ',
 'top-M': ' ',
 'top-R': ' '}
In [26]:
theBoard['mid-M'] = 'X'

img The first move

In [27]:
theBoard['top-L'] = 'O'
theBoard['top-M'] = 'O'
theBoard['top-R'] = 'O'
theBoard['mid-L'] = 'X'
theBoard['low-R'] = 'X'

img Player O wins

Convert dictionary to output

In [28]:
def printBoard(board):
  print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
  print('-----')
  print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
  print('-----')
  print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

The type() Function

In [29]:
type(42)
Out[29]:
int
In [30]:
type('42')
Out[30]:
str
In [31]:
type(3.14)
Out[31]:
float
In [32]:
type(theBoard)
Out[32]:
dict
In [33]:
type(theBoard['top-R'])
Out[33]:
str